package com.dnake.utils;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.hardware.Camera;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.PowerManager;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;


import com.dnake.WeKerApplication;
import com.dnake.panel.HomeActivity;
import com.dnake.receiver.PhoneStatListener;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.List;

import static com.bumptech.glide.gifdecoder.GifHeaderParser.TAG;

/**
 * Created by lenovo on 2016/5/24.
 */
public class AppUtils {
    private static long lastClickTime;

    //防止多次点击
    public synchronized static boolean isNotFastClick() {
        long time = System.currentTimeMillis();
        if ( time - lastClickTime > 1000) {
            lastClickTime = time;
            return true;
        }
        lastClickTime = time;
        return false;
    }

//    /**
//     * 重置4G模块
//     */
//    public static void reset4G(rkctrl m_rkctrl){
//        m_rkctrl.exec_io_cmd(15, 0);
//        SystemClock.sleep(500);
//        m_rkctrl.exec_io_cmd(15, 1);
////        ShellUtils.execCommand("echo AT+RESET >/dev/ttyUSB0 ",true);
//    }
    /**
     * 需要权限:android.permission.GET_TASKS
     *
     * @param context
     * @return
     */
    public static boolean isTopActivity(Context context) {
        ActivityManager am = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
        if (tasks != null && !tasks.isEmpty()) {
            ComponentName topActivity = tasks.get(0).topActivity;
            if (topActivity.getPackageName().equals(context.getApplicationContext().getPackageName())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 检测网络信号
     * @param context
     */
    public static void detectNetwork(Context context){
        //获取telephonyManager
        TelephonyManager mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        //监听信号强度
        mTelephonyManager.listen(new PhoneStatListener(), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
    }
    /**
     * 设置窗口 隐藏bottom按钮
     * @param activity
     */
    public static void setWindows(Activity activity){
        //隐藏标题栏
        activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //隐藏状态栏
        //定义全屏参数
        int flag= WindowManager.LayoutParams.FLAG_FULLSCREEN;
//        //获得当前窗体对象
        Window window=activity.getWindow();
//        //设置当前窗体为全屏显示
        window.setFlags(flag, flag);
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
        window.setAttributes(params);
    }
    /**
     * 系统重启
     * @param context
     */
    public static void reBoot(Context context){
        PowerManager pManager=(PowerManager) context.getSystemService(Context.POWER_SERVICE);  //重启到fastboot模式
        pManager.reboot("");
    }

    /**
     * 重启APP
     * @param activity
     */
    public static void rebootApp(Activity activity){
        Intent newIntent = new Intent(activity, HomeActivity.class);
        PendingIntent restartIntent = PendingIntent.getActivity(activity, 0, newIntent, Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        //退出程序
        AlarmManager mgr = (AlarmManager)activity.getSystemService(Context.ALARM_SERVICE);
        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 2000, restartIntent); // 1秒钟后重启应用
        WeKerApplication.getContext().finishActivity();
    }

    public static String get10Random(){
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i <10 ; i++) {
            sb.append((int)(Math.random()*10)+"");
        }
        return sb.toString();
    }
    //int转byte
    public static byte[] intToBytes(int num) {
           byte[] b = new byte[4];
           for (int i = 0; i < 4; i++) {
                b[i] = (byte) (num >>> (24 - i * 8));
               }
           return b;
    }

    /**
     * 切换软键盘的状态
     * 如当前为收起变为弹出,若当前为弹出变为收起
     */
    public static void toggleInput(Context context){
        InputMethodManager inputMethodManager =
                (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
    }

    /**
     * 强制隐藏输入法键盘
     */
    public static void hideInput(Context context, View view){
        InputMethodManager inputMethodManager =
                (InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

        /**
         * 判断摄像头是否可用
         * 主要针对6.0 之前的版本，现在主要是依靠try...catch... 报错信息，感觉不太好，
         * 以后有更好的方法的话可适当替换
         *
         * @return
         */
    public  static boolean isCameraCanUse() {
        boolean canUse = true;
        Camera mCamera = null;
        try {
            mCamera = Camera.open();
            // setParameters 是针对魅族MX5 做的。MX5 通过Camera.open() 拿到的Camera
            // 对象不为null
            Camera.Parameters mParameters = mCamera.getParameters();
            mCamera.setParameters(mParameters);
        } catch (Exception e) {
            canUse = false;
        }
        if (mCamera != null) {
            mCamera.release();
        }
        return canUse;
    }

    public static String byte2hex(byte[] b) {
        StringBuffer hs = new StringBuffer(b.length);
        String stmp = "";
        int len = b.length;
        for (int n = 0; n < len; n++) {
            stmp = Integer.toHexString(b[n] & 0xFF);
            if (stmp.length() == 1)
                hs = hs.append("0").append(stmp);
            else {
                hs = hs.append(stmp);
            }
        }
        return String.valueOf(hs);
    }
    //获取本地IP
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
//            Log.e("WifiPreference IpAddress", ex.toString());
        }

        return null;
    }
    public static String getLocalMacAddressFromWifiInfo(Context context){
        WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        return info.getMacAddress();
    }

    /**
     * 获取设备的mac地址
     * @return
     */
    public static String getMacAddress()
    {
        String strMacAddr = "";
        byte[] b;
        try
        {
            NetworkInterface NIC = NetworkInterface.getByName("eth0");
            b = NIC.getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++)
            {
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        }
        catch (SocketException e)
        {
            e.printStackTrace();
        }
        Log.i(TAG, "--- DVB Mac Address : " + strMacAddr);

        return strMacAddr;
    }



    public static byte[] HexString2Bytes(String hexstr) {
        byte[] b = new byte[hexstr.length() / 2];
        int j = 0;
        for (int i = 0; i < b.length; i++) {
            char c0 = hexstr.charAt(j++);
            char c1 = hexstr.charAt(j++);
            b[i] = (byte) ((parse(c0) << 4) | parse(c1));
        }
        return b;
    }
    private static int parse(char c) {
        if (c >= 'a')
            return (c - 'a' + 10) & 0x0f;
        if (c >= 'A')
            return (c - 'A' + 10) & 0x0f;
        return (c - '0') & 0x0f;
    }
}
